package com.opennews.openplatform.familyexpenseapi.service

import com.opennews.openplatform.familyexpenseapi.config.AppConfigProperties
import com.opennews.openplatform.familyexpenseapi.entity.Tables.REGION
import com.opennews.openplatform.familyexpenseapi.entity.tables.records.RegionRecord
import com.opennews.openplatform.familyexpenseapi.jooq.DSLContextWrapper
import com.opennews.openplatform.familyexpenseapi.jooq.RecordHelper
import org.jooq.DSLContext
import org.springframework.core.env.Environment
import org.springframework.stereotype.Service

@Service
class RegionService(
    private val appConfigProperties: AppConfigProperties,
    private val dslContext: DSLContext,
    private val dslContextWrapper: DSLContextWrapper,
    private val env: Environment,
) {
    /**
     * Prepares the initial data for the region.
     */
    fun init() {
        if (!dslContextWrapper.exists(REGION)) {
            val records = listOf(
                createRecord("柬埔寨", "cambodia"),
                createRecord("马来西亚", "malaysia"),
                createRecord("新加坡", "singapore"),
                createRecord("泰国", "thailand"),
            )

            dslContext.batchInsert(records)
        }
    }

    /**
     * Gets the region flag URL based on its name.
     *
     * @param name The region name.
     * @return The full URL of the region flag.
     */
    fun getFlagUrl(name: String?): String =
        if (!name.isNullOrBlank()) "${appConfigProperties.resource.httpBaseUrl}${appConfigProperties.resource.regionFlagUrl}/${name.lowercase()}.png" else ""


    /**
     * Queries all regions.
     *
     * @return A list of maps containing the following keys:
     * - `id`: String representing the region ID.
     * - `name`: String representing the region name.
     * - `title`: String representing the region title.
     * - `flagUrl`: String representing the region flag URL.
     */
    fun queryAll(): List<Map<String, Any>> =
        dslContext
            .select(
                REGION.ID.`as`("id"),
                REGION.NAME.`as`("name"),
                REGION.TITLE.`as`("title"),
            )
            .from(REGION)
            .orderBy(REGION.NAME.asc())
            .fetch()
            .map { record ->
                record.intoMap().toMutableMap().apply {
                    put("flagUrl", getFlagUrl(get("name").toString()))
                }
            }

    private fun createRecord(title: String, name: String): RegionRecord {
        return dslContext.newRecord(REGION).apply {
            RecordHelper.setCommonFields(this)
            this.title = title
            this.name = name
        }
    }
}